package com.irdstudio.efp.esb.api.rest.psd.credit;

import com.alibaba.fastjson.JSONObject;
import com.irdstudio.basic.framework.core.constant.EsbRetCodeStandard;
import com.irdstudio.basic.framework.core.util.UUIDUtil;
import com.irdstudio.efp.console.service.facade.PubSysInfoService;
import com.irdstudio.efp.ctr.service.facade.PsdSxctrConfirmLogService;
import com.irdstudio.efp.ctr.service.vo.PsdSxctrConfirmLogVO;
import com.irdstudio.efp.esb.api.bean.psd.credit.req.PsdSxCtrCusConfirmReqBean;
import com.irdstudio.efp.esb.api.bean.psd.credit.resp.PsdSxCtrCusConfirmRespBean;
import com.irdstudio.efp.esb.api.common.GroupeInterface;
import com.irdstudio.efp.esb.api.rest.EsbController;
import com.irdstudio.efp.esb.api.service.esb.EsbRespServcie;
import com.irdstudio.efp.esb.common.server.req.EsbReqServiceBean;
import com.irdstudio.efp.esb.common.server.resp.EsbRespServiceBean;
import com.irdstudio.efp.limit.service.facade.LmtPrdContService;
import com.irdstudio.efp.limit.service.vo.LmtPrdContVO;
import com.irdstudio.efp.nls.service.facade.PsdSendTaxRecordService;
import com.irdstudio.efp.nls.service.facade.sx.NlsCreditInfoService;
import com.irdstudio.efp.nls.service.vo.PsdSendTaxRecordVO;
import com.irdstudio.efp.nls.service.vo.sx.NlsCreditInfoVO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.*;

@RestController
@RequestMapping("/esb")
public class PsdSxCtrCusConfirmController implements EsbController {

    /**
     * 日志信息
     */
    private final Logger logger = LoggerFactory.getLogger(PsdSxCtrCusConfirmController.class);

    @Autowired
    private NlsCreditInfoService nlsCreditInfoService;

    @Autowired
    private LmtPrdContService lmtPrdContService;

    @Autowired
    private EsbRespServcie<PsdSxCtrCusConfirmRespBean> esbRespServcie;

    @Autowired
    private PubSysInfoService pubSysInfoService;

    @Autowired
    private PsdSendTaxRecordService psdSendTaxRecordService;

    @Autowired
    private PsdSxctrConfirmLogService psdSxctrConfirmLogService;

    @PostMapping("/SERVICE_30220008_07")
    public EsbRespServiceBean doRecv(@Validated @ModelAttribute("esbReqServiceBean") EsbReqServiceBean esbReqServiceBean, BindingResult bindingResult1,
                                     @Validated @ModelAttribute("psdSxCtrCusConfirmReqBean") PsdSxCtrCusConfirmReqBean psdSxCtrCusConfirmReqBean, BindingResult bindingResult2, Exception exception) {
        final String glblSrlNo = esbReqServiceBean.getSysHead().getGlblSrlNo();
        logger.info("发起授信申请：" + JSONObject.toJSONString(psdSxCtrCusConfirmReqBean) + "全局流水号" + glblSrlNo);
        // 设置系统头对象
        setSysHeadFieldThreadLocal(esbReqServiceBean);
        //返回信息
        PsdSxCtrCusConfirmRespBean psdSxCtrCusConfirmRespBean = new PsdSxCtrCusConfirmRespBean();
        try {
            // 参数校验
            if (Objects.nonNull(exception)) {
                //如果异常不为空，那么处理异常返回信息
                return esbRespServcie.getEsbRespServiceBeanByException(
                        esbReqServiceBean,
                        exception,
                        psdSxCtrCusConfirmRespBean,
                        EsbRetCodeStandard.JKYDCSJYBTG);
            }
            ArrayList<String> cusConfirmFlags = new ArrayList<>();
            cusConfirmFlags.add("0");
            cusConfirmFlags.add("1");
            cusConfirmFlags.add("999");
            if (!cusConfirmFlags.contains(psdSxCtrCusConfirmReqBean.getCusConfirmFlag())) {
                return esbRespServcie.getEsbRespServiceBeanByException(
                        esbReqServiceBean,
                        new Exception("不合法的客户确认状态"),
                        psdSxCtrCusConfirmRespBean,
                        EsbRetCodeStandard.JKYDCSJYBTG);
            }

            //根据授信申请流水号查询数据
            NlsCreditInfoVO nlsCreditInfoVO = nlsCreditInfoService.queryByLmtApplySeq(psdSxCtrCusConfirmReqBean.getLmtApplySeq());
            if (Objects.isNull(nlsCreditInfoVO)) {
                return esbRespServcie.getEsbRespServiceBeanByException(
                        esbReqServiceBean,
                        new Exception("根据授信流水号查询到的授信申请记录为空"),
                        psdSxCtrCusConfirmRespBean,
                        EsbRetCodeStandard.JKYDCSJYBTG);
            }
            if ("999".equals(psdSxCtrCusConfirmReqBean.getCusConfirmFlag())) {
                //如果客户输入999 则判断客户是否存在确认记录
                List<PsdSxctrConfirmLogVO> psdSxctrConfirmLogVOS = psdSxctrConfirmLogService.queryBySxApplySeq(psdSxCtrCusConfirmReqBean.getLmtApplySeq());
                if (psdSxctrConfirmLogVOS.isEmpty()) {
                    return esbRespServcie.getEsbRespServiceBeanByException(
                            esbReqServiceBean,
                            new Exception("根据授信流水号查询到客户确认记录为空"),
                            psdSxCtrCusConfirmRespBean,
                            EsbRetCodeStandard.KHXXJYBTG);
                } else {
                    return esbRespServcie.getSucessBean(esbReqServiceBean, psdSxCtrCusConfirmRespBean, EsbRetCodeStandard.SUCCESS);
                }
            }

            //判断授信申请记录是否为有效状态
            if (!"02".equals(nlsCreditInfoVO.getApprvSts())) {
                return esbRespServcie.getEsbRespServiceBeanByException(
                        esbReqServiceBean,
                        new Exception("非有效状态的授信记录"),
                        psdSxCtrCusConfirmRespBean,
                        EsbRetCodeStandard.JKYDCSJYBTG);
            }
            LmtPrdContVO lmtPrdContVOPkParam = new LmtPrdContVO();
            lmtPrdContVOPkParam.setLmtApplySeq(nlsCreditInfoVO.getLmtApplySeq());
            LmtPrdContVO lmtPrdContVO = lmtPrdContService.queryByPk(lmtPrdContVOPkParam);
            if (Objects.isNull(lmtPrdContVO)) {
                return esbRespServcie.getEsbRespServiceBeanByException(
                        esbReqServiceBean,
                        new Exception("查询到的额度数据为空"),
                        psdSxCtrCusConfirmRespBean,
                        EsbRetCodeStandard.JKYDCSJYBTG);
            }
            if (!"02".equals(lmtPrdContVO.getLmtStatus())) {
                return esbRespServcie.getEsbRespServiceBeanByException(
                        esbReqServiceBean,
                        new Exception("非有效状态的额度记录"),
                        psdSxCtrCusConfirmRespBean,
                        EsbRetCodeStandard.JKYDCSJYBTG);
            }
            //如果客户填了否
            if ("0".equals(psdSxCtrCusConfirmReqBean.getCusConfirmFlag())) {
                //需要修改授信申请记录为失效
                nlsCreditInfoService.updateApprvSts("06", nlsCreditInfoVO.getLmtApplySeq());
                //需要修改额度数据为失效
                lmtPrdContService.updateLmtStatus("03", lmtPrdContVO.getLmtContNo());
                //回写税局 还款日期等于授信终止日期
                insertTaxRecord(nlsCreditInfoVO);
            }
            insertPsdSxCtrConfirmLog(psdSxCtrCusConfirmReqBean);
            //返回报文
            return esbRespServcie.getSucessBean(esbReqServiceBean, psdSxCtrCusConfirmRespBean, EsbRetCodeStandard.SUCCESS);
        } catch (Exception ex) {
            logger.error("全局流水号" + glblSrlNo + "授信申请出现异常，异常信息为：" + ex.getMessage());
            return esbRespServcie.getEsbRespServiceBeanByException(esbReqServiceBean, ex, psdSxCtrCusConfirmRespBean, EsbRetCodeStandard.OTHERS_EXCEPTION);
        }
    }

    private void insertPsdSxCtrConfirmLog(@ModelAttribute("psdSxCtrCusConfirmReqBean") @Validated({GroupeInterface.psd.class}) PsdSxCtrCusConfirmReqBean psdSxCtrCusConfirmReqBean) {
        PsdSxctrConfirmLogVO psdSxctrConfirmLogVO = new PsdSxctrConfirmLogVO();
        psdSxctrConfirmLogVO.setId(UUIDUtil.getUUID());
        psdSxctrConfirmLogVO.setSxApplySeq(psdSxCtrCusConfirmReqBean.getLmtApplySeq());
        psdSxctrConfirmLogVO.setConfirmType(psdSxCtrCusConfirmReqBean.getCusConfirmFlag());
        psdSxctrConfirmLogVO.setCreateTime(new Date());
        psdSxctrConfirmLogService.insert(psdSxctrConfirmLogVO);
    }

    @ModelAttribute("esbReqServiceBean")
    public EsbReqServiceBean getReqEsbHeadBean(HttpServletRequest request) {
        logger.info("获取 ESB请求系统头和请求应用头对象!");
        EsbReqServiceBean esbReqServiceBean = (EsbReqServiceBean) request.getAttribute("esbReqServiceBean");
        return esbReqServiceBean;
    }

    @ModelAttribute("psdSxCtrCusConfirmReqBean")
    public PsdSxCtrCusConfirmReqBean getReqEsbBodyBean(HttpServletRequest request) {
        logger.info("获取 ESB请求体！");
        String esbReqBody = (String) request.getAttribute("esbReqBody");
        return JSONObject.parseObject(esbReqBody, PsdSxCtrCusConfirmReqBean.class);
    }

    public void insertTaxRecord(NlsCreditInfoVO nlsCreditInfoVO) {
        try {
            PsdSendTaxRecordVO psdSendTaxRecordVO = new PsdSendTaxRecordVO();
            psdSendTaxRecordVO.setTaxNo("");
            psdSendTaxRecordVO.setApplySeq(nlsCreditInfoVO.getLmtApplySeq());
            psdSendTaxRecordVO.setApplyStatus("Y");
            psdSendTaxRecordVO.setApplyMsg("客户确认非本人签订的授信合同，终止该授信额度");
            psdSendTaxRecordVO.setSendType("6");
            psdSendTaxRecordVO.setBizDate(pubSysInfoService.getOpenday("1001"));
            psdSendTaxRecordVO.setHandStatus("N");
            psdSendTaxRecordVO.setHandNum(0);
            psdSendTaxRecordVO.setCreateTime(new Date());
            psdSendTaxRecordService.insert(psdSendTaxRecordVO);
        } catch (Exception ex) {
            logger.error("还款成功插入回写税局表发生异常", ex);
        }
    }
}